package middleware

import (
	"net/http"
	"vblog/apps/token"
	"vblog/ioc"
	"vblog/response"

	"github.com/gin-gonic/gin"
)

// gin.HandlerFunc
// // HandlerFunc defines the handler used by gin middleware as return value.
// type HandlerFunc func(*Context)

// 中间件 ，是否有权限
func Auth(ctx *gin.Context) {

	// 从gin ctx中获取token
	accessToken, err := ctx.Cookie(token.CookieName)
	if err != nil {
		response.Failed(ctx, ErrAuthFailed.WithMessage(err.Error()).WithHttpCode(http.StatusUnauthorized))
		ctx.Abort()
	}

	// 获取到at ,验证token
	tk, err := ioc.
		Controller.
		Get(token.AppName).(token.Service).
		ValidateToken(ctx, token.NewValidateTokenRequest(accessToken))

	if err != nil {
		response.Failed(ctx, ErrAuthFailed.WithMessage(err.Error()).WithHttpCode(http.StatusUnauthorized))
		ctx.Abort()
	}

	// 如果有token ,保存到gin context中，传递

	// Gin的context
	// Keys is a key/value pair exclusively for the context of each request.
	// Keys map[string]any
	ctx.Set(token.GinCookieName, tk)

	// 继续执行
	ctx.Next()
}
